<?php
namespace app\api\controller;

use think\Controller;
use think\Config;
use think\Validate;
use think\request;
use app\api\model\Banner;
use app\api\model\News;
use app\api\model\NewsType;
use app\api\model\UserInfo;
use app\api\model\UserAuth;
use app\api\model\Integral;
use app\api\model\User as UserModel;
use app\api\model\OrderComment;

class User extends Auth
{
    /**
     * 获取用户的昵称头像认证状态
     */    
    public function mycore()
    {
        $result = UserInfo::alias('m')
            ->where('m.user_id', $this->user['user_id'])
            ->join('jk_user_authentications a', 'a.user_id = m.user_id', 'LEFT')
            ->field('m.nickname, m.user_icon_url, a.status')
            ->find();

        return success($result, '数据获取成功');
    }

    /**
     * 获取用户的信息
     */
    public function index()
    {
        $result = UserInfo::where('user_id', $this->user['user_id'])
            ->field('nickname, sex, qq, email, praise, commonly, negative_comment, descs, create_at')
            ->find();

        return success($result, '数据获取成功');
    }

    /**
     * 修改个人资料
     */
    public function personal()
    {
        $result = UserInfo::where('user_id', $this->user['user_id'])
            ->field('user_id, nickname, qq, sex, descs')
            ->find();

        return success($result, '数据获取成功');
    }

    /**
     * 提交个人资料
     */
    public function edit_personal()
    {
        $validate = new Validate([
            ['nickname', 'require|length:5,16', '昵称不能为空|昵称长度不正确'],
            ['qq', 'number|length:4,16', 'QQ格式不正确|不是有效QQ'],
            ['descs', 'require|length:5,50', '描述不能为空|描述长度不正确'],
            ['sex', 'require', '请选择性别'],
        ]);
        $param = $this->request->param();
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        if ($this->user['user_id'] != $param['user_id']) {
            return error('信息不一致');
        }
        $where = ['user_id'=>$this->user['user_id']];
        $update = [
            'nickname' => $param['nickname'],
            'qq' => $param['qq'],
            'descs' => $param['descs'],
            'sex' => $param['sex']
        ];
        $falg = UserInfo::where($where)->update($update);
        if ($falg) {
            return success(0, '更新成功');
        }
        return error('更新失败');
    }

    /**
     * 提交认证资料
     */
    public function add_auth()
    {
        $param = $this->request->param();
        if($param['type'] == 1) {
            $validate = new Validate([
                ['true_name', 'require', '请输入姓名'],
                ['phone','require|max:11|/^1[3-8]{1}[0-9]{9}$/','请输入手机号码|手机号码最多不能超过11个字符|手机号码格式不正确'],
                ['card_id','require|/^[A-Za-z0-9]+$/|max:18','请输入身份证|请正确填写身份证号码|身份证号码不正确'],
                ['pic', 'require', '请上传图片'],
            ]);
        }else{
            $validate = new Validate([
                ['true_name', 'require', '请输入企业名称'],
                ['phone','require|max:11|/^1[3-8]{1}[0-9]{9}$/','请输入手机号码|手机号码最多不能超过11个字符|手机号码格式不正确'],
                ['card_id','require|/^[A-Za-z0-9]+$/|max:18','请输入企业号码|请正确填写企业号码|企业号码不正确'],
                ['pic', 'require', '请上传图片'],
            ]);
        }
        if(!$validate->check($param)) {
            return error($validate->getError());
        }

//        $file = request()->file('pic');
//        if ($file) {
//            $info = $file->validate(['size'=>15678000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'authentications' );
//            if($info){
//                $pathinfo = pathinfo($info->getSaveName());
//                $pic_url = $info->getSaveName();
//                $param['pic'] = $pic_url;
//            } else{
//                return error($file->getError());
//            }
//        } else{
//            return error('请上传图片');
//        }
        $where = ['user_id'=>$this->user['user_id']];
        $update = [
            'true_name' => $param['true_name'],
            'type' => $param['type'],
            'phone' => $param['phone'],
            'card_id' => $param['card_id'],
            'pic' => $param['pic'],
            'status' => 3,
            'sub_time' => time()
        ];

        $falg = Userauth::where($where)->update($update);
        if ($falg) {
            return success(0, '提交成功');
        }
        return error('提交失败');
    }

    /**
     * 积分详细
     */
    public function integral()
    {
        $result = Integral::where('user_id', $this->user['user_id'])
            ->field('type, content, menber, channel, create_at')
            ->order('create_at desc')
            ->paginate($this->number);

        $data = formatPage('result', $result);

        return success($data, '数据获取成功');
    }

    /**
     * 文章列表
     */
    public function newslist()
    {
        $result = News::alias('n')
        ->where('n.user_id', $this->user['user_id'])
        ->join('jk_news_types f', 'f.id = n.father_id', 'LEFT') //一级分类
        ->join('jk_news_types s', 's.id = n.second_id', 'LEFT') //二级分类
        ->join('jk_news_types t', 't.id = n.type_id', 'LEFT') //三级分类
        ->field('n.id, n.title, n.status, n.create_at, f.name as father_name,  s.name as second_name, f.modular')
        ->order('n.update_time DESC')->paginate();

        $data = formatPage('result', $result);

        return success($data, '数据获取成功');
    }

    /**
     * 提交文章
     */
    public function newsrelease()
    {
        $validate = new Validate([
            ['title', 'require|length:2,30', '请填写标题|标题长度不正确'],
            ['father_id', 'require|number', '请选择一级分类|请选择一级分类'],
            ['second_id', 'require|number', '请选择二级分类|请选择一级分类'],
            ['text', 'require', '请填写内容'],
        ]);
        $param = $this->request->param();
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        if (!array_key_exists('type_id',$param)) {
            $param['type_id'] = 0;
        }
        $parent_list = NewsType::where('pid',$param['second_id'])->select();

        if (!empty($parent_list)) {
            if(empty($param['type_id'])){
                return error('请选择三级分类');
            }
        }

        $insert = new News([
            'user_id' => $this->user['user_id'],
            'father_id'  =>  $param['father_id'],
            'second_id' => $param['second_id'],
            'type_id' => $param['type_id'],
            'title' => $param['title'],
            'text' => $param['text'],
            'status' => 1,
            'type_id_aggregate' => $param['father_id'] .','. $param['second_id'] .','. $param['type_id'],
            'create_at' => time(),
            'update_time' => time()
        ]);
        $res = $insert->save();
        
        return success($res, '发布成功,等待审核');        
    }
    
    /**
     * 分类
     */
    public function typelist()
    {
        $param['pid'] = 0;
        $param['is_nav_show'] = 1;
        $result = NewsType::where($param)
            ->field('id, pid, name, modular')
            ->order('sort ASC,modular ASC')
            ->select();
        $list = [];
        foreach ($result as $k => $v) {
            $list[$k]['id'] = $v['id'];
            $list[$k]['pid'] = $v['pid'];
            $list[$k]['name'] = $v['name'];
            $list[$k]['modular'] = $v['modular'];
            $list[$k]['type'] = NewsType::where('pid',$v['id'])->field('id, pid, name, modular')->select();
        }

        return success($list, '数据获取成功');
    }

    /*
     * 用户签到
     */
    public function sign(Request $request = null)
    {
        $map['user_id'] = $this->user->user_id;
        $map['channel'] = 1;    //签到
        $res = Integral::whereTime('create_at', 'd')
            ->where($map)
            ->find();
        if (!empty($res)) {
            return error('你今天已经签到，请明天再来');
        }

        $is_ok = add_signin(1, 1, Config::get('web.sign'), $this->user->user_id, '签到');
        if ($is_ok) {
            Userinfo::where('user_id', $this->user->user_id)->setInc('integral', Config::get('web.sign'));

            return success(1, '签到成功');
        } else {
            return error('签到失败，请重新签到');
        }
    }

    //消息
    public function news()
    {
        $user_id = $this->user['user_id'];

        $order_comments = OrderComment::alias('c')
            ->join('jk_user_orders o', 'o.order_id = c.order_id', 'LEFT')
            ->where(['o.buyer_id|o.seller_id'=>$user_id, 'c.user_id'=>['neq',$user_id], 'is_new'=>1])
            ->field('c.*, o.buyer_id, o.seller_id')
            ->order('create_at DESC')->paginate($this->number);

        //正则匹配
        foreach ($order_comments as $key => $value){
            //把以<开头、>结尾的字符串用''替换 去除HTML标签
            $value->text = preg_replace('/<.*?>/', '', $value->text);
        }

        $list = formatPage('order_comments',$order_comments);

        return success($list, '数据获取成功');
    }
}
